package com.xhwl.centiotdata.suppliersystem.bailian;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.exception.ApplicationException;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/20/ 10:08
 */
@Service
public class GeneralBaiLianHandler {
    private static final Logger log = LoggerFactory.getLogger(GeneralBaiLianHandler.class);

    public JSONObject post(String path, Map<String, Object> params) {
        log.info("post path:{};params:{}", path, JSON.toJSONString(params));
        String result = null;
        try {
            result = HttpRequest
                    .post(path)
                    .body(JSON.toJSONString(params))
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("post path:{};params:{}; request failed!", path, JSON.toJSONString(params));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("post path:{};params:{};result is null!", path, JSON.toJSONString(params));
            throw new BusinessException();
        }
        log.info("post path:{};params:{};result:{}", path, JSON.toJSONString(params), result);
        JSONObject resultObject = JSON.parseObject(result);
        if (resultObject == null || resultObject.getIntValue("code") != 0) {
            log.error("post path:{};params:{};message:{}", path, JSON.toJSONString(params), resultObject.getString("message"));
            throw new BusinessException("BaiSi post failed!");
        }
        return resultObject;
    }

}
